package com.yx.cloud.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.iot.base.service.Response;
import com.iot.base.service.req.GetAuthCodeParam;
import com.iot.base.service.req.ResetPasswordParam;
import com.iot.base.service.resp.ChangePasswordResponse;
import com.iot.base.service.resp.GetVerifyCodeResponse;
import com.iot.common.utils.Event;
import com.iot.common.utils.LogUtils;
import com.iot.sweeper.AppContext;
import com.yx.cloud.R;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.bean.CountryCodeBean;
import com.yx.cloud.country.CountryActivity;
import com.yx.cloud.databinding.RetrievepasswordActivityBinding;
import com.yx.cloud.utils.AtyContainer;
import com.yx.cloud.utils.CountryCodeUtils;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.LanguageUtils;
import com.yx.cloud.utils.RegularCheckUtils;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

/**
 * 创建时间 : 2018/12/25.
 * 创建人 :
 * 功能描述 :找回密码选择方式界面
 */
public class RetrievePasswordActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "RetrievePasswordActivity";
    private String account;
    private String type;
    private String mCountryCode, verificationCode, newPassWord;
    private RetrievepasswordActivityBinding binding;
    private TimeCount time;

    @Override
    public void onCreate() {
        binding = RetrievepasswordActivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initData();
    }

    @SuppressLint("LongLogTag")
    private void initData() {
        //自动获取当前国家代码
        // String contryCode = CountryCodeUtils.getCountryZipCode(this);
        String systemLanguage = LanguageUtils.getSystemLanguage(this);
        String substring = systemLanguage.substring(3, 5);
        ArrayList<CountryCodeBean> codeList = CountryCodeUtils.getCountryCodeList(this);
        for (int i = 0; i < codeList.size(); i++) {
            if (substring.equals("" + codeList.get(i).getLocale())) {
                String countryName = codeList.get(i).getName();
                LogUtils.i("-------------------------tvCountryCode :" + codeList.get(i).getName());
                binding.tvRetrieveSelectRegion.setText(countryName);
                mCountryCode = codeList.get(i).getCode() + "";
                break;
            }
        }
        binding.btnFindNext.setEnabled(false);

        String user_account = getIntent().getStringExtra("user_account");//内部修改密码过来时使用
        if (user_account != null) {
            binding.tvPassWordTitle.setText(R.string.U_Pw_Edit);
            binding.btnFindNext.setText(R.string.MY_Pw_Edit);
            binding.ivRetrieveArrow.setVisibility(View.GONE);
            binding.tbPasswordHide.setVisibility(View.GONE);
            binding.rlRetrieveSelectRegion.setEnabled(false);
            binding.etFindPhonenum.setEnabled(false);
            if (!user_account.equals("")) {
                binding.etFindPhonenum.setText(user_account);
            }
        }
//        setHintByCountryCode();

        /**
         * 对帐号密码输入框进行监听
         */
        binding.etFindPhonenum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

                if (!"".equals(editable.toString().trim()) &&
                        binding.etVerificationCode.length() >= 4 &&
                        binding.etSubmitSetNewPassWord.length() >= 6 &&
                        binding.etSubmitNewPassWord.length() >= 6) {
                    binding.btnFindNext.setEnabled(true);
                } else {
                    binding.btnFindNext.setEnabled(false);
                }
            }
        });
        /**
         * 对帐号密码输入框进行监听
         */
        binding.etSubmitSetNewPassWord.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() < 6) {
                    binding.btnFindNext.setEnabled(false);
                    return;
                }
                if (!"".equals(editable.toString().trim()) &&
                        binding.etVerificationCode.length() >= 4 &&
                        binding.etSubmitSetNewPassWord.length() >= 6 &&
                        binding.etSubmitNewPassWord.length() >= 6) {
                    binding.btnFindNext.setEnabled(true);
                } else {
                    binding.btnFindNext.setEnabled(false);
                }
            }
        });
        binding.etSubmitNewPassWord.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() < 6) {
                    binding.btnFindNext.setEnabled(false);
                    return;
                }
                if (!"".equals(editable.toString().trim()) &&
                        binding.etVerificationCode.length() >= 4 &&
                        binding.etSubmitSetNewPassWord.length() >= 6 &&
                        binding.etSubmitNewPassWord.length() >= 6) {
                    binding.btnFindNext.setEnabled(true);
                } else {
                    binding.btnFindNext.setEnabled(false);
                }
            }
        });
        binding.etVerificationCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() < 4) {
                    binding.btnFindNext.setEnabled(false);
                    return;
                }
                if (!"".equals(editable.toString().trim()) &&
                        binding.etVerificationCode.length() >= 4 &&
                        binding.etSubmitSetNewPassWord.length() >= 6 &&
                        binding.etSubmitNewPassWord.length() >= 6) {
                    binding.btnFindNext.setEnabled(true);
                } else {
                    binding.btnFindNext.setEnabled(false);
                }
            }
        });

        binding.ivRetrievePWReturn.setOnClickListener(this);
        binding.btnFindNext.setOnClickListener(this);
        binding.rlRetrieveSelectRegion.setOnClickListener(this);
        binding.tbPasswordHide.setOnClickListener(this);
        binding.tvRetrievePassWordGetVerificationCode.setOnClickListener(this);
        binding.tbSubmitSetPassword.setOnClickListener(this);
        binding.tbSubmitAffirmPassword.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (RomUtils.isFastClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.iv_retrieve_PW_return:
                finish();
                break;
            case R.id.tv_retrievePassWordGetVerificationCode:
                if (time == null) {
                    //获取验证码计时
                    time = new TimeCount(60000, 1000);
                    time.start();
                }
                //获取验证码
                GetAuthCodeParam param = new GetAuthCodeParam();
                account = binding.etFindPhonenum.getText().toString().trim();
                param.setAccount(account);
                param.setCountryCode(mCountryCode);
                param.setType(GetAuthCodeParam.TYPE_RESET_PWD);
                AppContext.getAccountService().getAuthCode(param);
                break;
            case R.id.btn_find_next:
                Log.d(TAG, "    IIIIIIIII-a----");
                account = binding.etFindPhonenum.getText().toString().trim();
                verificationCode = binding.etVerificationCode.getText().toString().trim();
                String setNewPassWord = binding.etSubmitSetNewPassWord.getText().toString().trim();
                String newPassWord = binding.etSubmitNewPassWord.getText().toString().trim();
                //判断是否输入了验证码/手机号
                if (account.isEmpty()) {
                    Toast.makeText(this, getString(R.string.U_T_Un_NoFormat), Toast.LENGTH_LONG).show();
                    return;
                }
                if (!setNewPassWord.equals(newPassWord)) {
                    Toast.makeText(this, getString(R.string.U_T_Pw_NoAgain), Toast.LENGTH_LONG).show();
                    return;
                }
                if (RegularCheckUtils.isMobile(account)) {
                    type = "phone";
                } else {
                    if (RegularCheckUtils.isEmail(account)) {
                        type = "emall";
                    } else {
                        Toast.makeText(this, getString(R.string.U_T_Un_NoFormat), Toast.LENGTH_LONG).show();
                        return;
                    }
                }
                //校验验证码
                ResetPasswordParam resetPasswordParam = new ResetPasswordParam();
                resetPasswordParam.setAccount(account);
                resetPasswordParam.setNewPassword(newPassWord);
                resetPasswordParam.setCountryCode(mCountryCode);
                resetPasswordParam.setCode(verificationCode);
                if (RegularCheckUtils.isMobile(account)) {
                    resetPasswordParam.setAccountType(1);//手机号
                } else {
                    resetPasswordParam.setAccountType(2);//邮箱
                }
                AppContext.getAccountService().resetPassword(resetPasswordParam);

                break;
            case R.id.rl_Retrieve_selectRegion:
                Intent intenta = new Intent(this, CountryActivity.class);
                startActivityForResult(intenta, 1);
                break;

            case R.id.tb_password_hide:
                binding.etFindPhonenum.setText("");
                break;
            case R.id.tb_submit_setPassword:
                if (binding.tbSubmitSetPassword.isChecked()) {
                    binding.etSubmitSetNewPassWord.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                } else {
                    binding.etSubmitSetNewPassWord.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                }
                binding.etSubmitSetNewPassWord.setSelection(binding.etSubmitSetNewPassWord.getText().toString().trim().length());
                break;
            case R.id.tb_submit_AffirmPassword:
                if (binding.tbSubmitAffirmPassword.isChecked()) {
                    binding.etSubmitNewPassWord.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                } else {
                    binding.etSubmitNewPassWord.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                }
                binding.etSubmitNewPassWord.setSelection(binding.etSubmitNewPassWord.getText().toString().trim().length());
                break;
        }
    }

    @SuppressLint("LongLogTag")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_GET_AUTH_CODE:
                //修改验证码获取成功
                if (event.isResult()) {
                    //成功 不处理
                } else {
                    GetVerifyCodeResponse response = (GetVerifyCodeResponse) event.getContent();
                    if (response.getErrorCode() == GetVerifyCodeResponse.ERROR_REGISTER_CODE_USER_EXIST) {
                        //注册验证码的用户存在
                        ToastUtil.showShort(this, getString(R.string.L_T_Register_Un_Existed));
                    } else if (response.getErrorCode() == GetVerifyCodeResponse.ERROR_CHANGE_PASSWORD_USER_NOT_EXIST) {
                        //修改密码验证码的用户不存在
                        ToastUtil.showShort(this, getString(R.string.U_T_Un_No));
                    } else if (response.getErrorCode() == GetVerifyCodeResponse.ERROR_REQUEST_COUNT_LIMIT) {
                        //验证码请求次数限制
                        ToastUtil.showShort(this, getString(R.string.U_T_Code_TimesLimit));
                    } else if (response.getErrorCode() == GetVerifyCodeResponse.ERROR_REQUEST_FREQUENCY_LIMIT) {
                        //验证码请求太过频繁 一分钟三次
                        ToastUtil.showShort(this, getString(R.string.U_T_Code_Frequently));
                    }else if (response.getErrorCode() == GetVerifyCodeResponse.ERROR_INVALID_ACCOUNT_FORMAT) {
                        //账号格式错误
                        ToastUtil.showShort(this, getString(R.string.U_T_Un_NoFormat));
                    } else if (response.getErrorCode() == GetVerifyCodeResponse.ERROR_NETWORK) {
                        ToastUtil.showShort(this, getString(R.string.U_T_Network_Err));
                    } else if (response.getErrorCode() == GetVerifyCodeResponse.ERROR_SERVER) {
                        ToastUtil.showShort(this, getString(R.string.U_T_Server_Err));
                    } else {
                        ToastUtil.showShort(this, getString(R.string.U_UnknownErr));
                    }
                }
                break;
            case Event.MESSAGE_TYPE_RESET_PASSWORD:
                //重置新密码后登录
                if (event.isResult()) {
                    //手机号登录
                    Toast.makeText(this, getString(R.string.U_T_EditPw_Success), Toast.LENGTH_SHORT).show();
                    AtyContainer.getInstance().finishAllActivity(); //在登录界面点击返回键退出程序
                    Intent_utils.enterIntent(this, LoginActivity.class);
                } else {
                    ChangePasswordResponse changePasswordResponse = (ChangePasswordResponse) event.getContent();
                    if (changePasswordResponse.getErrorCode() == ChangePasswordResponse.ERROR_VERIFY_CODE) {
                        //验证码错误
                        ToastUtil.showShort(this, getString(R.string.U_T_Code_No));
                    } else if (changePasswordResponse.getErrorCode() == ChangePasswordResponse.ERROR_VERIFY_CODE_EXPIRED) {
                        //验证码过期
                        ToastUtil.showShort(this, getString(R.string.U_T_Code_Expired));
                    } else if (changePasswordResponse.getErrorCode() == ChangePasswordResponse.ERROR_CHANGE_PASSWORD_USER_NOT_EXIST) {
                        ToastUtil.showShort(this, getString(R.string.U_T_Un_No));
                    }  else if (changePasswordResponse.getErrorCode() == Response.ERROR_NETWORK) {
                        ToastUtil.showShort(this, getString(R.string.U_T_Network_Err));
                    } else if (changePasswordResponse.getErrorCode() == Response.ERROR_SERVER) {
                        ToastUtil.showShort(this, getString(R.string.U_T_Server_Err));
                    } else {
                        ToastUtil.showShort(this, getString(R.string.U_UnknownErr));
                    }
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == 2) {
                String countryCode = data.getStringExtra("countryCode");
                String countryName = data.getStringExtra("countryName");
//                String en = data.getStringExtra("en");
                binding.tvRetrieveSelectRegion.setText(countryName);
                mCountryCode = countryCode;
//                setHintByCountryCode();
            }
        }
    }

//    private void setHintByCountryCode() {
//        if (!mCountryCode.equals("86")) {
//            binding.etFindPhonenum.setHint(getString(R.string.email));
//        } else {
//            binding.etFindPhonenum.setHint(getString(R.string.Please_enter_register_phone_email));
//        }
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            binding.tvRetrievePassWordGetVerificationCode.setClickable(false);
            binding.tvRetrievePassWordGetVerificationCode.setText(getResources().getString(R.string.U_AgainGet_Btn) + "(" + millisUntilFinished / 1000 + ")");
        }

        @Override
        public void onFinish() {
            binding.tvRetrievePassWordGetVerificationCode.setText(getResources().getString(R.string.U_GetCode_Btn));
            binding.tvRetrievePassWordGetVerificationCode.setClickable(true);
            time = null;
        }
    }
}
